package com.ws.control;

import com.alibaba.fastjson.JSON;
import com.ws.dao.SssfmNxYthServerDao;
import com.ws.entity.SssfmNxYthServer;
import com.ws.response.NxYthHttpResponse;
import com.ws.utils.InitKeyHttpUtil;
import com.ws.utils.NXHttpUtil;
import com.ws.utils.safeUtil.TranSM4Utils;
import com.ws.utils.sm.SM2Utils;
import com.ws.utils.sm.SM4Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName YthSmsController
 * @Description YthSmsController
 * @Author gxx
 * @Date 2020/11/30 19:19
 * @Version 1.0
 */
@RestController
@RequestMapping("/ythSmsController")
public class YthSmsController {


    @Autowired
    private InitKeyHttpUtil initKeyHttpUtil;

    @Autowired
    private SssfmNxYthServerDao sssfmNxYthServerDao;

    @RequestMapping("/relushServer")
    public void relushServer(){
        initKeyHttpUtil.init();
        SssfmNxYthServer applyLongServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "applyLongTermKey");
        SssfmNxYthServer confirmServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "confirmLongTermKey");
    }

    @RequestMapping("/getLongKey")
    public void getLongKey() throws Exception{
        System.out.println("========registerSysPubKey注册接口开始=======");
        NxYthHttpResponse registerSysPubKey = InitKeyHttpUtil.registerSysPubKey(InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "registerSysPubKey"));
        System.out.println("========查询平台SM2公钥开始=======");
        NxYthHttpResponse queryExchPubKey = InitKeyHttpUtil.queryExchPubKey(InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "queryExchPubKey"));
        System.out.println("========获取长密钥开始=======");
        SssfmNxYthServer applyLongServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "applyLongTermKey");
        applyLongServer.setSelfPrtKey(registerSysPubKey.getSelfPrtKey());
        applyLongServer.setSelfPblKey(registerSysPubKey.getSelfPblKey());
        applyLongServer.setOpsPblKey(queryExchPubKey.getOpsPblKey());
        NxYthHttpResponse applyLongResponse = InitKeyHttpUtil.applyLongTermKey(applyLongServer);
        System.out.println("========获取长密要======="+applyLongResponse.getLongKey());
        System.out.println("========获取长密钥结束=======");

        System.out.println("========确认密钥开始=======");
        SssfmNxYthServer confirmServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub",   "confirmLongTermKey");
        confirmServer.setLongKeyAck(applyLongResponse.getLongKeyAck());
        confirmServer.setOpsPblKey(queryExchPubKey.getOpsPblKey());
        NxYthHttpResponse confirmLongTermKey = InitKeyHttpUtil.confirmLongTermKey(confirmServer);
        System.out.println("========确认密钥结束=======");
        if("0".equals(confirmLongTermKey.getResult())){
            updataAllInfo( applyLongResponse.getLongKey(),registerSysPubKey.getSelfPrtKey(),registerSysPubKey.getSelfPblKey(),queryExchPubKey.getOpsPblKey());
        }

    }

    public void updataAllInfo(String longKey,String selfPrtKey,String selfPblKey,String opsPblKey){
        SssfmNxYthServer updata = new SssfmNxYthServer();
        updata.setLongKey(longKey);
        updata.setSelfPrtKey(selfPrtKey);
        updata.setSelfPblKey(selfPblKey);
        updata.setOpsPblKey(opsPblKey);
        sssfmNxYthServerDao.updateByPrimaryKeySelective(updata);
    }

    @RequestMapping("/pushPayMainInfo")
    public String pushPayMainInfo() throws Exception {
        SssfmNxYthServer confirmServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("640000", "pushPayMainInfo");
        NxYthHttpResponse tempKey = getTempKey(confirmServer.getSeTargetsyscode(),confirmServer.getSeTargetservicecode());
        String sm4Key = tempKey.getData().getKey();
        System.out.println("---秘钥："+sm4Key);
        String xmlMsg = "{\"Bus_method\":\"addRealPay\",\"province\":\"640000\",\"year\":\"2020\",\"datalist\":[{\"agency_code\":\"640000121001\",\"bgt_id\":\"\",\"currency_code\":\"81\",\"est_rat\":\"\",\"exp_func_code\":\"2090199\",\"foreign_amt\":\"\",\"fund_type_code\":\"11411\",\"gov_bgt_eco_code\":\"\",\"pay_acct_bank_name\":\"宁夏银行股份有限公司营业部\",\"pay_acct_name\":\"宁夏回族自治区财政厅社会保障基金专户\",\"pay_acct_no\":\"100010188900048773-0001\",\"pay_alloc_cert_id\":\"af9ed96700ae49798134959f0cf35611\",\"pay_amt\":\"100.00\",\"payee_acct_bank_name\":\"宁夏银行股份有限公司营业部\",\"payee_acct_name\":\"宁夏回族自治区财政厅社会保障基金专户\",\"payee_acct_no\":\"100010188900048773-0001\",\"pro_code\":\"\",\"receiver_code\":\"\",\"use_des\":\"宁夏回族自治区财政厅9月企业职工基本养老保险基金 社会保险待遇支出\"}],\"appid\":\"realpay\"}";
        System.out.println("加密前报文："+xmlMsg);
        String baowen = TranSM4Utils.encryptData_CBC(xmlMsg, sm4Key.substring(0, 16), sm4Key.substring(16));
//        SM4Utils sm4Utils = new SM4Utils();
//        sm4Utils.secretKey = sm4Key;
//        String baowen = sm4Utils.encryptData_CBC(xmlMsg);
//        String baowen = SM4Utils.encryptData_ECB(xmlMsg, sm4Key);
        System.out.println("加密后报文:"+baowen);
        System.out.println("pushPayMainInfo报文发送开始");
        String res = NXHttpUtil.doPost(confirmServer.getUrl(), this.packHeader(confirmServer, tempKey.getData().getToken()), baowen, 6000);
        System.out.println("解密前返回："+res);

        String resCbc = TranSM4Utils.decryptData_CBC(res, sm4Key.substring(0, 16), sm4Key.substring(16));

//        String resCbc = sm4Utils.decryptData_CBC(res);

        System.out.println("解密后返回"+resCbc);
        return resCbc;


    }

    public Map packHeader(SssfmNxYthServer sssfmNxYthServer,String token) {
        Map header = new HashMap();
        header.put("Content-Type", "application/json");
        header.put("SE_sysCode", sssfmNxYthServer.getSeSyscode());//平台分配的业务系统编号
        header.put("SE_userId", sssfmNxYthServer.getSeUserid());//平台分配的账号ID
        header.put("SE_password", sssfmNxYthServer.getSePassword());//平台分配的账号密码
        header.put("SE_targetSysCode", sssfmNxYthServer.getSeTargetsyscode());//目标系统编码
        header.put("SE_targetServiceCode", sssfmNxYthServer.getSeTargetservicecode());//目标接口编码
        header.put("SE_token", token);
        System.out.println("Http-Header头信息："+ JSON.toJSONString(header));
        return header;
    }

    @RequestMapping("/getTempKey")
    public NxYthHttpResponse getTempKey(HttpServletRequest request) throws Exception {
        SssfmNxYthServer confirmServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "applyTempKey");
        confirmServer.setSeTargetservicecode(request.getParameter("seTargetservicecode"));
        confirmServer.setSeTargetsyscode(request.getParameter("seTargetsyscode"));
//        confirmServer.setLongKeyAck(applyLongResponse.getLongKeyAck());
        NxYthHttpResponse confirmLongTermKey = InitKeyHttpUtil.applyTempKey(confirmServer);
        return confirmLongTermKey;

    }

    public NxYthHttpResponse getTempKey(String seTargetsyscode,String seTargetservicecode) {
        NxYthHttpResponse confirmLongTermKey = null;
        try {
            SssfmNxYthServer confirmServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "applyTempKey");
            confirmServer.setSeTargetservicecode(seTargetservicecode);
            confirmServer.setSeTargetsyscode(seTargetsyscode);
            confirmLongTermKey = InitKeyHttpUtil.applyTempKey(confirmServer);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        return confirmLongTermKey;
    }
}
